import { Select } from '@alifd/next';
import React, { useEffect, useState } from 'react';
import { getItems } from './api';
import { SelectProps } from '@alifd/next/types/select';

interface DictItemSelectProps extends SelectProps {
  dictId: string;
  itemId: string;
}

/**
 * 获取字典下的字典项拓展属性值
 * @param dictId 字典名
 * @param itemId 字典项名
 * @returns Select
 */
function DictItemExtrasSelect({ dictId, itemId, ...props }: DictItemSelectProps) {
  const [data, setData] = useState<Array<Object>>([]);

  useEffect(() => {
    (async function fetchData() {
      const res = await getItems(dictId, itemId);
      const tempData: Array<Object> = [];
      for (const key in res.extras) {
        if (Object.prototype.hasOwnProperty.call(res.extras, key)) {
          const element = res.extras[key];
          tempData.push({
            label: key,
            value: element?.value
          })
        }
      }
      setData(tempData);
    })();
  }, []);

  return (
    <Select
      hasClear
      dataSource={data}
      // style={{ width: '100%' }}
      {...props}
    />
  );
}

export default DictItemExtrasSelect;
